package com.example.rssreader.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.rssreader.entity.RssFeed;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * RSS源数据访问层接口
 * 继承MyBatis Plus的BaseMapper，提供基础的CRUD操作
 * 
 * @author RSS Reader Team
 * @version 1.0.0
 * @since 2024-01-01
 */
@Mapper
public interface RssFeedMapper extends BaseMapper<RssFeed> {

    /**
     * 分页查询RSS源列表
     * 按创建时间倒序排列
     * 
     * @param page 分页参数
     * @return 分页结果
     */
    @Select("SELECT * FROM rss_feed WHERE deleted = 0 ORDER BY created_at DESC")
    IPage<RssFeed> selectFeedPage(Page<RssFeed> page);

    /**
     * 根据URL查询RSS源
     * 用于检查RSS源是否已存在
     * 
     * @param url RSS源URL
     * @return RSS源实体，如果不存在则返回null
     */
    @Select("SELECT * FROM rss_feed WHERE url = #{url} AND deleted = 0 LIMIT 1")
    RssFeed selectByUrl(@Param("url") String url);

    /**
     * 查询所有活跃的RSS源
     * 用于定时同步任务
     * 
     * @return RSS源列表
     */
    @Select("SELECT * FROM rss_feed WHERE deleted = 0 ORDER BY last_updated ASC")
    List<RssFeed> selectAllActiveFeeds();

    /**
     * 根据关键词搜索RSS源
     * 在标题和描述中进行模糊搜索
     * 
     * @param page    分页参数
     * @param keyword 搜索关键词
     * @return 分页结果
     */
    @Select("SELECT * FROM rss_feed " +
            "WHERE deleted = 0 " +
            "AND (title LIKE CONCAT('%', #{keyword}, '%') " +
            "OR description LIKE CONCAT('%', #{keyword}, '%')) " +
            "ORDER BY created_at DESC")
    IPage<RssFeed> searchFeeds(Page<RssFeed> page, @Param("keyword") String keyword);

    /**
     * 统计RSS源总数
     * 
     * @return RSS源总数
     */
    @Select("SELECT COUNT(*) FROM rss_feed WHERE deleted = 0")
    Long countActiveFeeds();

    /**
     * 获取最近更新的RSS源
     * 
     * @param limit 限制数量
     * @return RSS源列表
     */
    @Select("SELECT * FROM rss_feed " +
            "WHERE deleted = 0 AND last_updated IS NOT NULL " +
            "ORDER BY last_updated DESC " +
            "LIMIT #{limit}")
    List<RssFeed> selectRecentlyUpdatedFeeds(@Param("limit") Integer limit);
}